package com.example.design.pay.strategy.factory;

import com.example.design.pay.strategy.Context.PayContext;
import com.example.design.pay.strategy.PayStrategyInterface;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


//工厂模式具体工厂角色
@Component
public class PayContextFactory extends AbstractPayContextFactory<PayContext> {
    //创建Map数据结构作为缓存 存储PayContext
    private static final Map<String, PayContext> payContexts = new ConcurrentHashMap<>();

    //根据payType获取PayContext
    @Override
    public PayContext getContext(Integer payType) {
        //根据payType定位枚举类
        StrategyEnum strategyEnum =
                payType == 1 ? StrategyEnum.alipay :
                        payType == 2 ? StrategyEnum.wechat :
                                null;
        if (strategyEnum == null) {
            throw new UnsupportedOperationException("不支持的支付类型");
        }
        PayContext payContext = payContexts.get(strategyEnum.name());
        //第一次调用，
        if (payContext == null) {
            try {
                //通过反射创建 payContext
                PayStrategyInterface payStrategy = (PayStrategyInterface) Class.forName(strategyEnum.getValue()).newInstance();
                //将具体策略作为入参，创建PayContext对象
                PayContext context = new PayContext(payStrategy);
                //将PayContext对象放入缓存
                payContexts.put(strategyEnum.name(), context);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return payContexts.get(strategyEnum.name());
    }
}
